<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/31
 * Time: 15:57
 */

namespace app\index\logic;


use app\admin\logic\MoneyLogic;
use app\common\utils\Constant;
use app\common\utils\WeChatUtils;
use think\cache\driver\Redis;
use think\Config;
use think\Db;
use think\Exception;

class UserLogic
{
    /**
     * 根据token获取用户信息
     * @param $token
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserByToken($token)
    {
        if (empty($token)) {
            return array('status' => 0, 'error' => 'token不能为空');
        }
        $user_id = $this->getUserIdByToken($token);
        $user = $this->getUserById($user_id);
        if (!$user) {
            return array('status' => 0);
        }
        $user['token'] = $token;
        return array('status' => 1, 'data' => $user);
    }

    /**
     * 获取用户信息 通过id
     * @param $user_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getUserById($user_id)
    {
        $user = model('Member')
            ->where(array('id' => $user_id))
            ->field(['id', 'name', 'organization', 'phone', 'commit_num'], false)
            ->find();
        return $user;
    }

    /**
     * 获取用户id token
     * @param $token
     * @return mixed
     */
    public function getUserIdByToken($token)
    {
        $redis = new Redis();
        $user_id = $redis->get($token);
        return $user_id;
    }

    /**
     * 获取用户信息 通过微信授权code
     * @param $code
     * @return mixed
     */
    public function getUserByCode($code)
    {
        Db::startTrans();
        try {
            if (empty($code)) {
                return array('status' => 0, 'error' => 'code不能为空');
            }
            $we_chat = Config::get('WeChat');
            $utils = new WeChatUtils($we_chat['app_id'], $we_chat['app_secret'], $we_chat['token']);
            $result = $utils->getHtmlAccessToken($code);
            $userInfo = $utils->getUserInfo($result->access_token, $result->openid);
            $user = $this->saveOrUpdateUser($result->openid, $userInfo);
            $redis = new Redis();
            $token = $this->generateToken($user['open_id'], $user['id']);
            $redis->set($token, $user['id']);
            Db::commit();
            $user['token'] = $token;
            return array('status' => 1, 'data' => $user);
        } catch (Exception $e) {
            Db::rollback();
//            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    /**
     * 会员登录
     * @param $phone
     * @param $password
     * @return mixed
     * @internal param $code
     */
    public function Login($phone, $password, $ip)
    {
        Db::startTrans();
        try {
            if (empty($phone)) {
                return array('status' => 0, 'error' => '手机号不能为空');
            }
            if (empty($password)) {
                return array('status' => 0, 'error' => '密码不能为空');
            }
            $user = model('Member')
                ->field(['id', 'name', 'password', 'organization', 'phone', 'commit_num'], false)
                ->where(array('phone' => $phone))
                ->where(array('is_delete' => 0))
                ->find();
            if (!$user) {
                return array('status' => 0, 'error' => '账号不存在');
            }
            if ($user['password'] != $password) {
                return array('status' => 0, 'error' => '密码错误');
            }
            $redis = new Redis();
            $token = $this->generateToken($user['phone'], $user['id']);

            $redis->set($token, $user['id']);
            $login_log = array('ip' => $ip, 'create_time' => time(), 'member_id' => $user['id']);
            model('LoginLog')->create($login_log);
            Db::commit();
            $user['token'] = $token;
            return array('status' => 1, 'data' => $user);
        } catch (Exception $e) {
            Db::rollback();
//            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }

    /**
     * 获取会员审核数量
     * @return array
     * @internal param $token
     */
    public function getMemeberVerifyNum($token)
    {
        $data = array('verifySuccess' => 0, 'verifyFail' => 0, 'verifying' => 0);
        Db::startTrans();
        try {
            $user = $this->getUserByToken($token);
            $result = model('VerifyLog')->where(array('member_id' => $user['data']['id']))->select();
            foreach ($result as $key => &$value) {
                switch ($value['status']) {
                    case 0:
                        $data['verifying']++;
                        $data['verifying_name'][$key]['name'] = $value['chinese_name'];
                        break;
                    case 1:
                        $data['verifySuccess']++;
                        $data['verifySuccess_name'][$key]['name'] = $value['chinese_name'];
                        break;
                    case 2:
                        $data['verifyFail']++;
                        $data['verifyFail_name'][$key]['name'] = $value['chinese_name'];
                        break;
                }
            }
            Db::commit();
            return array('status' => 1, 'data' => $data);
        } catch (Exception $e) {
            Db::rollback();
//            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }
    /**
     * 获取会员搜索历史
     * @return array
     * @internal param $token
     */
    public function getMemeberAccessLog($token)
    {
        Db::startTrans();
        try {
            $user = $this->getUserByToken($token);
            $result = model('AccessLog')
                ->field(['keyword'], false)->where(array('member_id' => $user['data']['id']))->order('id desc')->limit(10)->select();
            $result = array_unique($result);
            Db::commit();
            return array('status' => 1, 'data' => $result);
        } catch (Exception $e) {
            Db::rollback();
//            return array('status' => 0, 'error' => $e->getMessage());
            return array('status' => 0, 'error' => "数据出错");
        }
    }



    /**
     * 创建或更新用户信息
     * @param $open_id
     * @param $user_info
     * @return $this|array|false|\PDOStatement|string|\think\Model
     */
    public function saveOrUpdateUser($open_id, $user_info)
    {
        $open_id = $open_id . '';
        $user = model('User')
            ->field(['nickname','is_manager','user_type',], true)
            ->where(array('open_id' => $open_id))
            ->find();
        if (!$user) {
            //创建用户
            $user_info = $this->makeUser($user_info);
            $user_info['create_time'] = time();
            $user_info['open_id'] = $open_id;
            $user_info['is_manager'] = 0;
            $user_info['user_type'] = Constant::USER_TYPE_GENERAL;
            $user = model('User')->create($user_info);
        } else {
            $user_info = $this->makeUser($user_info);
            $user->save($user_info);
        }
        return $user;
    }

    public function generateToken($open_id, $user_id)
    {
        return substr(md5(md5($open_id) . 'key' . $user_id . '' . time()), 0, 30);
    }

    private function makeUser($userInfo)
    {
        $user = [];
        $userInfo = (array)$userInfo;
        if (isset($userInfo) && isset($userInfo['nickname'])) {
            $user['nickname'] = match_chinese($userInfo['nickname']);
            $user['avatar'] = $userInfo['headimgurl'];
            $sex = $userInfo['sex'] . '';
            $user['sex'] = $sex == '2' ? 1 : 0;
        }
        return $user;
    }

}